package com.luoye_lj.dogcontroller;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.ParcelUuid;
import android.text.SpannableString;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.luoye_lj.dogcontroller.adapter.ListViewAdapter;
import com.luoye_lj.dogcontroller.dialog.BigTextToast;
import com.luoye_lj.dogcontroller.log.ArLog;
import com.luoye_lj.dogcontroller.util.FastPermissions;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private String TAG=getClass().getSimpleName();
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int REQUEST_DISCOVERABLE_BT = 2;
    private FastPermissions fastPermissions;
    ProgressBar progressBar;
    Button scanDevicesBtn;
    ListView devicesLv;
    Button stopDevicesBtn;

    boolean permissionsGranted=false;

    private BluetoothAdapter bluetoothAdapter;
    private ArrayList<BluetoothDevice> deviceList = new ArrayList<>();

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device!=null&&!deviceList.contains(device)) {
                    @SuppressLint("MissingPermission")
                    String deviceName=device.getName();
                    if(deviceName!=null&&deviceName.startsWith("NB-")){
                        deviceList.add(device);
                    }
                }
                // 刷新列表
                loadData();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });


        // 申请必要权限
        fastPermissions = new FastPermissions(this);
        permissions();

        // 加载组件
        progressBar=findViewById(R.id.progressBar);
        scanDevicesBtn=findViewById(R.id.scanDevicesBtn);
        devicesLv=findViewById(R.id.devicesLv);
        stopDevicesBtn=findViewById(R.id.stopDevicesBtn);
        // 为扫描按钮添加点击事件
        scanDevicesBtn.setOnClickListener(v -> {
            // 扫描设备
            scanDevices();
        });
        devicesLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = deviceList.get(position);
                String deviceName=device.getName();
                if(deviceName==null){
                    deviceName="未知设备";
                }

                ArLog.i(TAG,"device:"+device);

                // 连接设备
                Intent intent = new Intent(MainActivity.this, ControlActivity.class);
                intent.putExtra("device", device);
                startActivity(intent);
//                BigTextToast.makeText(MainActivity.this, "点击了"+deviceName, Toast.LENGTH_SHORT).show();
            }
        });
        loadData();
        stopDevicesBtn.setOnClickListener(v -> {
            // 停止扫描
            stopScan();
        });

//        // 设为可被发现按钮点击事件
//        btnDiscoverable.setOnClickListener(v -> {
//            if (!bluetoothAdapter.isEnabled()) {
//                Toast.makeText(MainActivity.this, "请先启用蓝牙", Toast.LENGTH_SHORT).show();
//                return;
//            }
//            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
//            startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_BT);
//        });

        // 注册广播接收器
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bluetoothAdapter!=null){
            stopScan();
        }
        // 取消注册广播接收器
        unregisterReceiver(receiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "蓝牙已启用", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "用户拒绝了启用蓝牙", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_DISCOVERABLE_BT) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "设备现在可被发现", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "用户拒绝了设备可被发现", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 权限获取
    private void permissions(){
        ArrayList<String> permissionLists=new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {// Android 版本大于等于 Android12 时
            permissionLists.add(Manifest.permission.BLUETOOTH_SCAN);
            permissionLists.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            permissionLists.add(Manifest.permission.BLUETOOTH_CONNECT);
            permissionLists.add(Manifest.permission.ACCESS_FINE_LOCATION);
            permissionLists.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        } else { // Android 版本小于 Android12 及以下版本
            permissionLists.add(Manifest.permission.BLUETOOTH);
            permissionLists.add(Manifest.permission.BLUETOOTH_ADMIN);
            permissionLists.add(Manifest.permission.ACCESS_FINE_LOCATION);
            permissionLists.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }


        // 申请获取定位权限
        fastPermissions.need(permissionLists.toArray(new String[0]))
                .subscribe(new FastPermissions.Subscribe() {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
                    @Override
                    public void onResult(int requestCode, boolean allGranted, String[] permissions) {
                        if (allGranted){// 获取到权限
                            permissionsGranted=true;
                            initBluetooth();
                        }else{
                            //权限拒绝后进行的操作
                            BigTextToast.makeText(MainActivity.this, "权限被拒绝", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).request(2);
    }

    @SuppressLint("MissingPermission")
    private void initBluetooth(){
        // 初始化蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            runOnUiThread(() -> {
                Toast.makeText(MainActivity.this, "该设备不支持蓝牙", Toast.LENGTH_LONG).show();
            });
        }else {
            // 检查蓝牙是否已开启
            if (!bluetoothAdapter.isEnabled()) {
                // 开启蓝牙
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    }

    // 扫描设备方法
    @SuppressLint("MissingPermission")
    private void scanDevices() {
        progressBar.setVisibility(View.VISIBLE);
        // 清空设备列表
        deviceList.clear();
        // 刷新列表
        loadData();
        if(bluetoothAdapter==null){
            BigTextToast.showLargeToast(this,"该设备不支持蓝牙");
            return;
        }

//        // 获取已配对设备
//        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
//        pairedDevicesAdapter.clear();
//        if (pairedDevices.size() > 0) {
//            for (BluetoothDevice device : pairedDevices) {
//                pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
//            }
//        } else {
//            pairedDevicesAdapter.add("没有已配对设备");
//        }

        // 开始扫描设备
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
//        Toast.makeText(this, "正在扫描设备...", Toast.LENGTH_SHORT).show();

        // 60秒后停止扫描
        new Handler(Looper.getMainLooper()).postDelayed(this::stopScan, 60000);
    }
    @SuppressLint("MissingPermission")
    private void stopScan(){
        if(bluetoothAdapter==null){
            BigTextToast.showLargeToast(this,"该设备不支持蓝牙");
            return;
        }
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        progressBar.setVisibility(View.GONE);
    }

    @SuppressLint("MissingPermission")
    private void loadData(){
        ArrayList<HashMap<String,Object>> dataList=new ArrayList<HashMap<String,Object>>();
        for (int i = 0; i < deviceList.size(); i++) {
            BluetoothDevice device=deviceList.get(i);
            String deviceName=device.getName();
            if(deviceName==null){
                deviceName="未知设备";
            }
            HashMap<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("num", new SpannableString("" + (i+1)));
            dataMap.put("deviceNameTv", new SpannableString(deviceName));
            dataList.add(dataMap);
        }
        ListViewAdapter sa = new ListViewAdapter(this, devicesLv, dataList, R.layout.lvitem_device_info,
                new String[]{"num", "deviceNameTv"},
                new int[]{R.id.numTv, R.id.deviceNameTv});
        devicesLv.setAdapter(sa);
    }
}